package structual_pattern.proxy_pattern;

import sun.misc.ProxyGenerator;

import java.io.FileOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class StarProxy implements InvocationHandler {
    // 目标类，也就是被代理对象
    private Object target;

    public StarProxy(Object target) {
        this.target = target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 这里可以做增强
        System.out.println("收钱");

        Object result = method.invoke(target, args);

        return result;
    }

    // 生成代理类
    public Object creatProxyedObj() {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }

    public static void main(String[] args) throws Exception{
        Searcher searcher = (Searcher) new StarProxy(new RealSearcher()).creatProxyedObj();
        searcher.doSearch();
        //$Proxy0
        byte[] bytes = ProxyGenerator.generateProxyClass("$Proxy0", new Class[]{Searcher.class});
        FileOutputStream os = new FileOutputStream("D:\\IdeaProjects\\my_code\\test\\design_patterns\\src\\structual_pattern\\proxy_pattern\\$Proxy0.class");
        os.write(bytes);
        os.close();
    }

}
